#region Imported Namespaces
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;

using PHSRAG.Insight21.SearchContext;
using Calendar				= PHSRAG.WebControls.Calendar;
using DataAccess			= PHSRAG.Utility.DataAccess;
using SessionCachePolicy	= PHSRAG.Insight21.Policy.SessionCachePolicy;
using Policy				= PHSRAG.Insight21.Policy;
using UserContext			= PHSRAG.Insight21.Context.UserContext;
using Constants				= PHSRAG.Insight21.InsightUtilities.Constants;
#endregion

namespace PHSRAG.Insight21.InsightWebControls
{
	#region Class OverviewSearch
	/// <summary>
	/// The OverviewSearch control is used by agreement overview pages.
	/// </summary>
	[ToolboxData("<{0}:OverviewSearch runat=server />"), Designer(typeof(OverviewSearchDesigner))]
	public class OverviewSearch : BaseSearch, INamingContainer, ISearch
	{		
		#region Instance Variables
		private ControlCollection	controlCollection;
		private CheckBox		includeUserOrders;
		private DropDownList	accountNumber;
		private DropDownList	category;
		private DropDownList	daysBudgetEnding;		
		private DropDownList	salaryOnFundExpiring;
		private TextBox			employeeId;
		private Calendar		payFromDate;
		private Calendar		payToDate;
		private Calendar		expenseFromDate;
		private Calendar		expenseToDate;
		private Calendar		budgetEndDate;
		private Calendar		budgetStartDate;
        private Calendar revenueFromDate;
        private Calendar revenueToDate;
        private TextBox revenueAccountNumber;

		private Policy.ICachePolicy cachePolicy;

		private bool categoryAndAccountFilterVisible	= true;
		private bool budgetStartEndFilterVisible		= true;
		private bool budgetEndingFilterVisible			= true;
		private bool includeUserOrdersFilterVisible		= true;
        private bool employeeIdFilterVisible;
		private bool payFromToDateFilterVisible;
		private bool salaryOnFundExpiringFilterVisible;
		private bool expenseDateFilterVisible;
        private bool revenueDateFilterVisible;

		private const string CategoryChangedCommand		= "Category Changed";
		#endregion

		#region ISearch Members
		/// <summary>
		/// Set the value for all controls to their default values
		/// and resetting the cached state of the search context.
		/// Clear the items in the account number drop down list 
		/// as it is dependent on the Category
		/// </summary>
		public void Reset()
		{
			ResetControls(controlCollection);

			OverviewSearchContext searchContext = cachePolicy.GetCachedObject(OverviewSearchContext.CacheKey) as OverviewSearchContext;
			if (searchContext != null)
				searchContext.Reset(Page.Request.Url.ToString());

			if(categoryAndAccountFilterVisible)
			{
				accountNumber.Items.Clear();
				accountNumber.Items.Add(CommonSearch.SelectPrompt);
				accountNumber.Enabled = false;
				category.SelectedIndex = category.Items.IndexOf(category.Items.FindByText(CommonSearch.SelectPrompt));
			}

			if (BudgetStartEndFilterVisible)
			{
				budgetStartDate.Reset();
				budgetEndDate.Reset();
			}
			if (ExpenseDateFilterVisible)
			{
				expenseFromDate.Reset();
				expenseToDate.Reset();
			}

            if (RevenueDateFilterVisible)
            {
                revenueFromDate.Reset();
                revenueToDate.Reset();
            }
		}

		/// <summary>
		/// Get the search criteria from the common search context.
		/// </summary>
		public SearchCriteria SearchCriteria
		{
			get
			{
				return ((OverviewSearchContext)cachePolicy.GetCachedObject(OverviewSearchContext.CacheKey)).GetSearchCriteria(Page.Request.Url.ToString());
			}
		}


		/// <summary>
		/// Update the search criteria with the current values in all controls, store
		/// them in the OverviewSearchContext, and then return the search criteria.
		/// </summary>
		public SearchCriteria UpdateSearchCriteria()
		{
			UserContext userContext = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);
			return GetSearchCriteria(userContext.DomainUserId, controlCollection);
		}
		#endregion

		#region Protected Properties
		/// <summary>
		/// Determine if the control is in design mode. It is if there is not HTTP context.
		/// </summary>
		protected static bool IsDesignMode
		{
			get { return HttpContext.Current == null; }
		}
		#endregion

		#region public Properties
		/// <summary>
		///  Get/Set the visibility of the Category And Account Search Filter.
		/// </summary>
		public bool CategoryAndAccountFilterVisible
		{
			get { return categoryAndAccountFilterVisible;  }
			set { categoryAndAccountFilterVisible= value;}
		}

		/// <summary>
		///  Get/Set the visibility of the Budget Start End Search Filter.
		/// </summary>
		public bool BudgetStartEndFilterVisible
		{
			get { return budgetStartEndFilterVisible;  }
			set { budgetStartEndFilterVisible= value;}
		}

		/// <summary>
		///  Get/Set the visibility of the Budget Ending  Search Filter.
		/// </summary>
		public bool BudgetEndingFilterVisible
		{
			get { return budgetEndingFilterVisible;  }
			set { budgetEndingFilterVisible= value;}
		}

		/// <summary>
		///  Get/Set the visibility of the Include User Orders Search Filter.
		/// </summary>
		public bool IncludeUserOrdersFilterVisible
		{
			get { return includeUserOrdersFilterVisible;  }
			set { includeUserOrdersFilterVisible= value;}
		}

		/// <summary>
		///  Get/Set the visibility of the Employee Id Search Filter.
		/// </summary>
		public bool EmployeeIdFilterVisible
		{
			get { return employeeIdFilterVisible;  }
			set { employeeIdFilterVisible= value;}
		}

		/// <summary>
		///  Get/Set the visibility of the Pay From /To Date Search Filter.
		/// </summary>
		public bool PayFromToDateFilterVisible
		{
			get { return payFromToDateFilterVisible;  }
			set { payFromToDateFilterVisible= value;}
		}

		/// <summary>
		///  Get/Set the visibility of the Salary On Fund Expiring Search Filter.
		/// </summary>
		public bool SalaryOnFundExpiringFilterVisible
		{
			get { return salaryOnFundExpiringFilterVisible;  }
			set { salaryOnFundExpiringFilterVisible = value;}
		}

		/// <summary>
		///  Get/Set the visibility of the Expense date range Filter.
		/// </summary>
		public bool ExpenseDateFilterVisible
		{
			get { return expenseDateFilterVisible;  }
			set { expenseDateFilterVisible = value;}
		}

        /// <summary>
        ///  Get/Set the visibility of the Revenue date range Filter.
        /// </summary>
        public bool RevenueDateFilterVisible
        {
            get { return revenueDateFilterVisible; }
            set { revenueDateFilterVisible = value; }
        }
        
        /// <summary>
		/// Enumeration for pages to specify which dropdown to populate
		/// </summary>
		public enum DDL
		{
			Categories,
			AccountNumbers
		}

		/// <summary>
		/// Event raised to alert the page that the selected category has changed
		/// </summary>
		[Category("Action"), Description("Raised when the selected index in category dropdown changes")]
		public event CommandEventHandler CategoryChanged
		{
			add		{ Events.AddHandler(CategoryChangedCommand, value); }
			remove	{ Events.RemoveHandler(CategoryChangedCommand, value); }
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Get the unique-ID (client-side) for the specified type of drop-down-list.
		/// </summary>
		/// <param name="ddl">One of the drop-down-list types</param>
		/// <returns>Unique-id of the drop-down-list</returns>
		public string GetDDLID(DDL ddl)
		{
			switch (ddl)
			{
				case DDL.Categories: return (category == null) ? string.Empty : category.UniqueID;
				case DDL.AccountNumbers : return (accountNumber == null) ? string.Empty : accountNumber.UniqueID;
				default: return string.Empty;
			}
		}

		/// <summary>
		/// Get the unique-id (client-side) of the include-user-order checkbox.
		/// </summary>
		/// <returns>Unique-id</returns>
		public string GetIncludeUserOrdersID()
		{
			return (includeUserOrders == null) ? string.Empty : includeUserOrders.UniqueID;
		}

		/// <summary>
		/// Method for pages to supply data and populate the dropdownlist controls
		/// </summary>
		/// <param name="ddl">Integer value from enum to designate which control to populate</param>
		/// <param name="table">Data</param>
		/// <param name="textColumnName">Name of table column that contains the text for the ddl</param>
		/// <param name="valueColumnName">Name of table column that contains the value for the ddl</param>
		/// <param name="selectedValue">Value of item to set as selected</param>
		public void SetDDLData(int ddl, DataTable table, string textColumnName, string valueColumnName, string selectedValue)
		{
			EnsureChildControls();
			DropDownList ddlControl;
			if (ddl == (int)DDL.Categories)
			{
				ddlControl = category;
				cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];
				OverviewSearchContext searchContext = cachePolicy.GetCachedObject(OverviewSearchContext.CacheKey)
					as OverviewSearchContext;
				if (searchContext == null)
				{
					searchContext = new OverviewSearchContext(cachePolicy);
					DataTable categories = new DataTable();
					categories.Columns.Add("Category", table.Columns[textColumnName].DataType);
					categories.Columns.Add("CategoryId", table.Columns[valueColumnName].DataType);
					foreach(DataRow row in table.Rows)
						categories.Rows.Add(new object[]{row[textColumnName], row[valueColumnName]});
					searchContext.Categories = categories;
					searchContext.Cache();
					LoadDropDownList(ddlControl, categories, "Category", "CategoryId");
				}
				else
				{
					DataTable cachedCategories = searchContext.Categories;
					if(cachedCategories.Rows.Count > table.Rows.Count)
						LoadDropDownList(ddlControl, cachedCategories, "Category", "CategoryId");
					else
					{
						DataTable categories = new DataTable();
						categories.Columns.Add("Category", table.Columns[textColumnName].DataType);
						categories.Columns.Add("CategoryId", table.Columns[valueColumnName].DataType);
						foreach(DataRow row in table.Rows)
							categories.Rows.Add(new object[]{row[textColumnName], row[valueColumnName]});
						searchContext.Categories = categories;
						searchContext.Cache();
						LoadDropDownList(ddlControl, categories, "Category", "CategoryId");
					}
				}
			}
			else
			{
				ddlControl = accountNumber;
				LoadDropDownList(ddlControl, table, textColumnName, valueColumnName);
			}
			if(ddlControl.Enabled && !String.IsNullOrEmpty(selectedValue))
				ddlControl.SelectedIndex = ddlControl.Items.IndexOf(ddlControl.Items.FindByValue(selectedValue));
		}
        #endregion

		#region Virtual Methods
		/// <summary>
		/// Invoked by the method which builds the HTML representation of the control tree. Derived classes would typically
		/// return the HTML to be inserted into the stream AFTER the indicated row.
		/// </summary>
		/// <param name="currentRowNumber">The number (starting from 1) of the row that the HTML returned by this method
		/// would be inserted at.
		/// </param>
		/// <returns>HTML string to add at row number currentRowNumber</returns>
		protected virtual string GetHTML(int currentRowNumber)
		{
			return string.Empty;
		}
		#endregion

		#region Overrides
		protected override void OnInit(EventArgs e)
		{
			cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];
			OverviewSearchContext searchContext = cachePolicy.GetCachedObject(OverviewSearchContext.CacheKey)
				as OverviewSearchContext;
			if (searchContext == null)
			{
				searchContext = new OverviewSearchContext(cachePolicy);
			}

			EnsureChildControls();
			base.OnInit (e);
			searchContext.GetSearchCriteria(Page.Request.Url.ToString(), controlCollection);
		}

		/// <summary>
		/// Create all controls. Instantiate all the controls and generate
		/// the underlying HTML so that the controls shows up per the need.
		/// </summary>
		protected override void CreateChildControls()
		{
			CreateControls();
			GenerateControlTree();
		}

		/// <summary>
		/// Initialize the contents of all controls on first load. If the OverviewSearchContext is not cached yet, a
		/// new instance is created and cached.
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnLoad(EventArgs e)
		{
			try
			{
				cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];

				if (!Page.IsPostBack)
				{
					EnsureChildControls();

					OverviewSearchContext searchContext = cachePolicy.GetCachedObject(OverviewSearchContext.CacheKey)
						as OverviewSearchContext;
					if (searchContext == null)
					{
						searchContext = new OverviewSearchContext(cachePolicy);
						searchContext.Load(DataAccess.ConnectionString);
						searchContext.Cache();
					}
					SetControlState(searchContext.GetSearchCriteria(Page.Request.Url.ToString(), controlCollection));
				}
			}
			catch(Exception ex)
			{
				throw new Exception(Utility.ExceptionReport.GetExceptionInfo(ex,false));
			}
		}

        /// <summary>
        /// Set the state for all constituent controls, and register a client script block for the express purpose of
        /// validating the date ranges of all paired Calendar controls in this search block.
        /// </summary>
        /// <param name="e">Argument associated with the event</param>
        /// <remarks>
        /// <protocolId>Why are the actions taken in this method not being done on control load?</protocolId>
        /// <protocolId>During the non-postback construction of the control, the OnLoad method is invoked BEFORE the
        /// CreateChildControls method. The actual creation of constitutent controls are done within the context of
        /// the CreateChildControls methos. Setting the state of control relies on (obviously) the fact that the controls
        /// have been created. So, setting the state in OnLoad for the non-postback condition would fail.</protocolId>
        /// <protocolId>Interestingly, the sequence of method invocations reverses on postback: CreateChildControls is invoked
        /// before OnLoad.</protocolId>
        /// </remarks>
        protected override void OnPreRender(EventArgs e)
        {
            if (!IsDesignMode)
            {
                if (!Page.ClientScript.IsClientScriptBlockRegistered(Constants.ValidateDateRangeScriptKey))
                {
                    string script = string.Format(
                        "<script language=\"javascript\">\n" +
                        "function ValidateDateRange()\n" +
                        "{{\n" +
                        "\tif (document.getElementById(\"{0}\") != null)\n" +
                        "\t\tvar budgetStartText = document.getElementById(\"{0}\").value;\n" +
                        "\tif (document.getElementById(\"{1}\") != null)\n" +
                        "\t\tvar budgetEndText = document.getElementById(\"{1}\").value;\n" +
                        "\tif (document.getElementById(\"{2}\") != null)\n" +
                        "\t\tvar expenseFromText = document.getElementById(\"{2}\").value;\n" +
                        "\tif (document.getElementById(\"{3}\") != null)\n" +
                        "\t\tvar expenseToText = document.getElementById(\"{3}\").value;\n" +
                        "\tif (document.getElementById(\"{4}\") != null)\n" +
                        "\t\tvar payFromText = document.getElementById(\"{4}\").value;\n" +
                        "\tif (document.getElementById(\"{5}\") != null)\n" +
                        "\t\tvar payToText = document.getElementById(\"{5}\").value;\n" +
                        "\tif (document.getElementById(\"{6}\") != null)\n" +
                        "\t\tvar revenueFromText = document.getElementById(\"{6}\").value;\n" +
                        "\tif (document.getElementById(\"{7}\") != null)\n" +
                        "\t\tvar revenueToText = document.getElementById(\"{7}\").value;\n" +
                        "\tif (budgetStartText != null && budgetStartText != \"\" && budgetEndText != null && budgetEndText != \"\")\n" +
                        "\t{{\n" +
                        "\t\tvar budgetStartDate = new Date(budgetStartText);\n" +
                        "\t\tvar budgetEndDate = new Date(budgetEndText);\n" +
                        "\t\tif (budgetStartDate > budgetEndDate)\n" +
                        "\t\t{{\n" +
                        "\t\t\talert('Budget Start Date cannot be after Budget End Date.');\n" +
                        "\t\t\tdocument.getElementById(\"{1}\").focus();\n" +
                        "\t\t\treturn false;\n" +
                        "\t\t}}\n" +
                        "\t\treturn true;\n" +
                        "\t}}\n" +
                        "\tif (expenseFromText != null && expenseFromText != \"\" && expenseToText != null && expenseToText != \"\")\n" +
                        "\t{{\n" +
                        "\t\tvar expenseFromDate = new Date(expenseFromText);\n" +
                        "\t\tvar expenseToDate = new Date(expenseToText);\n" +
                        "\t\tif (expenseFromDate > expenseToDate)\n" +
                        "\t\t{{\n" +
                        "\t\t\talert('Expense From Date cannot be after Expense To Date.');\n" +
                        "\t\t\tdocument.getElementById(\"{3}\").focus();\n" +
                        "\t\t\treturn false;\n" +
                        "\t\t}}\n" +
                        "\t\treturn true;\n" +
                        "\t}}\n" +
                        "\tif (payFromText != null && payFromText != \"\" && payToText != null && payToText != \"\")\n" +
                        "\t{{\n" +
                        "\t\tvar payFromDate = new Date(payFromText);\n" +
                        "\t\tvar payToDate = new Date(payToText);\n" +
                        "\t\tif (payFromDate > payToDate)\n" +
                        "\t\t{{\n" +
                        "\t\t\talert('Pay From Date cannot be after Pay To Date.');\n" +
                        "\t\t\tdocument.getElementById(\"{5}\").focus();\n" +
                        "\t\t\treturn false;\n" +
                        "\t\t}}\n" +
                        "\t\treturn true;\n" +
                        "\t}}\n" +
                        "\tif (revenueFromText != null && revenueFromText != \"\" && revenueToText != null && revenueToText != \"\")\n" +
                        "\t{{\n" +
                        "\t\tvar revenueFromDate = new Date(revenueFromText);\n" +
                        "\t\tvar revenueToDate = new Date(revenueToText);\n" +
                        "\t\tif (revenueFromDate > revenueToDate)\n" +
                        "\t\t{{\n" +
                        "\t\t\talert('Revenue From Date cannot be after Revenue To Date.');\n" +
                        "\t\t\tdocument.getElementById(\"{7}\").focus();\n" +
                        "\t\t\treturn false;\n" +
                        "\t\t}}\n" +
                        "\t\treturn true;\n" +
                        "\t}}\n" +
                        "\treturn true;\n" +
                        "}}\n" +
                        "</script>\n",
                        (budgetStartDate == null) ? "" : budgetStartDate.SelectedDateClientId,
                        (budgetEndDate == null) ? "" : budgetEndDate.SelectedDateClientId,
                        (expenseFromDate == null) ? "" : expenseFromDate.SelectedDateClientId,
                        (expenseToDate == null) ? "" : expenseToDate.SelectedDateClientId,
                        (payFromDate == null) ? "" : payFromDate.SelectedDateClientId,
                        (payToDate == null) ? "" : payToDate.SelectedDateClientId,
                        (revenueFromDate == null) ? "" : revenueFromDate.SelectedDateClientId,
                        (revenueToDate == null) ? "" : revenueToDate.SelectedDateClientId);

                    Page.ClientScript.RegisterClientScriptBlock(GetType( ), Constants.ValidateDateRangeScriptKey, script);
                }
            }

            base.OnPreRender (e);
        }

		/// <summary>
		/// Handler for the event fired when the selected item in the category drop down is changed
		/// Load the account number drop down for the category and update the search criteria.
		/// </summary>
		/// <param name="sender">Control which raised the event</param>
		/// <param name="e">Argument associated with the event</param>
		protected void OnSelectedIndexChanged(object sender,EventArgs e)
		{
			try
			{
				CommandEventHandler handler = (CommandEventHandler)Events[CategoryChangedCommand];
				if (handler != null)
					handler(this, new CommandEventArgs(CategoryChangedCommand, 
						(category.SelectedItem.Value != CommonSearch.SelectPrompt) ? category.SelectedItem.Value : "0"));
			}
			catch(Exception ex)
			{
				throw new Exception(Utility.ExceptionReport.GetExceptionInfo(ex,false));
			}
		}
		#endregion

		#region Private Methods
		/// <summary>
		/// Create all controls in the CommonSearch.
		/// </summary>
		private void CreateControls()
		{
			Controls.Clear();
			controlCollection = new ControlCollection(this);

			if (CategoryAndAccountFilterVisible)
			{
				category = new DropDownList();
				category.ID = "categoryID";
				category.CssClass = "DataInput";
				category.SelectedIndexChanged += new EventHandler(OnSelectedIndexChanged);
				category.AutoPostBack = true;
				category.Attributes["Label"] = "Category";
				controlCollection.Add(category);
			}

			if (IncludeUserOrdersFilterVisible)
			{
				includeUserOrders = new CheckBox();
				includeUserOrders.ID = "includeUserOrders";
				includeUserOrders.Checked = false;
				//			includeUserOrders.Text = "Include User Orders";
				//			includeUserOrders.TextAlign = TextAlign.Left;
				includeUserOrders.CssClass = "DataInput";
				controlCollection.Add(includeUserOrders);
			}

			if (CategoryAndAccountFilterVisible)
			{
				accountNumber = new DropDownList();
				accountNumber.ID = "accountNumber";
				accountNumber.CssClass = "DataInput";
				accountNumber.Attributes["Label"] = "Account Number";
				controlCollection.Add(accountNumber);
			}

			if (BudgetStartEndFilterVisible)
			{
				budgetStartDate = new Calendar();
				budgetStartDate.ID = "budgetStartDate";
				budgetStartDate.Prompt = CommonSearch.SelectPrompt;
				budgetStartDate.Attributes["Label"] = "Budget Start Date";
				controlCollection.Add(budgetStartDate);

				budgetEndDate = new Calendar();
				budgetEndDate.ID = "budgetEndDate";
				budgetEndDate.Prompt = CommonSearch.SelectPrompt;
				budgetEndDate.Attributes["Label"] = "Budget End Date";
				controlCollection.Add(budgetEndDate);
			}

			if (BudgetEndingFilterVisible)
			{
				daysBudgetEnding = new DropDownList();
				daysBudgetEnding.ID = "daysBudgetEnding";
				daysBudgetEnding.CssClass = "DataInput";
				daysBudgetEnding.Items.Add(CommonSearch.SelectPrompt);
				daysBudgetEnding.Items.Add(new ListItem("30 Days", "30"));
				daysBudgetEnding.Items.Add(new ListItem("60 Days", "60"));
				daysBudgetEnding.Items.Add(new ListItem("90 Days", "90"));
				daysBudgetEnding.SelectedIndex = 0;
				daysBudgetEnding.Enabled = (daysBudgetEnding.Items.Count > 1);
				daysBudgetEnding.Attributes["Label"] = "Days Budget Ending";
				controlCollection.Add(daysBudgetEnding);
			}

			if (EmployeeIdFilterVisible)
			{
				employeeId = new TextBox();
				employeeId.ID = InsightUtilities.Constants.EmployeeIdKey;
				employeeId.CssClass = "DataInput";
				employeeId.Attributes["Label"] = "Employee ID";
				controlCollection.Add(employeeId);
			}

			if (SalaryOnFundExpiringFilterVisible || PayFromToDateFilterVisible)
			{
				payFromDate = new Calendar();
				payFromDate.ID = InsightUtilities.Constants.PayFromDateKey;
				payFromDate.Prompt = CommonSearch.SelectPrompt;
				payFromDate.Attributes["Label"] = "Pay From Date";
				controlCollection.Add(payFromDate);

				payToDate = new Calendar();
				payToDate.ID = InsightUtilities.Constants.PayToDateKey;
				payToDate.Prompt = CommonSearch.SelectPrompt;
				payToDate.Attributes["Label"] = "Pay To Date";
				controlCollection.Add(payToDate);

				salaryOnFundExpiring = new DropDownList();
				salaryOnFundExpiring.ID = "daysProjectEnding";
				salaryOnFundExpiring.CssClass = "DataInput";
				salaryOnFundExpiring.Items.Add(CommonSearch.SelectPrompt);
				salaryOnFundExpiring.Items.Add(new ListItem("30 Days", "30"));
				salaryOnFundExpiring.Items.Add(new ListItem("60 Days", "60"));
				salaryOnFundExpiring.Items.Add(new ListItem("90 Days", "90"));
				salaryOnFundExpiring.SelectedIndex = 0;
				salaryOnFundExpiring.Enabled = (salaryOnFundExpiring.Items.Count > 1);
				salaryOnFundExpiring.Attributes["Label"] = "Salary on Funds ending In";
				controlCollection.Add(salaryOnFundExpiring);
			}

			if (ExpenseDateFilterVisible)
			{
				expenseFromDate = new Calendar();
				expenseFromDate.ID = InsightUtilities.Constants.ExpenseFromDateKey;
				expenseFromDate.Prompt = CommonSearch.SelectPrompt;
				expenseFromDate.Attributes["Label"] = "Month from";
				controlCollection.Add(expenseFromDate);

				expenseToDate = new Calendar();
				expenseToDate.ID = InsightUtilities.Constants.ExpenseToDateKey;
				expenseToDate.Prompt = CommonSearch.SelectPrompt;
				expenseToDate.Attributes["Label"] = "Month to";
				controlCollection.Add(expenseToDate);
			}

            if (RevenueDateFilterVisible)
            {
                revenueFromDate = new Calendar();
                revenueFromDate.ID = InsightUtilities.Constants.RevenueFromDateKey;
                revenueFromDate.Prompt = CommonSearch.SelectPrompt;
                revenueFromDate.Attributes["Label"] = "Revenue From Date";
                controlCollection.Add(revenueFromDate);

                revenueToDate = new Calendar();
                revenueToDate.ID = InsightUtilities.Constants.RevenueToDateKey;
                revenueToDate.Prompt = CommonSearch.SelectPrompt;
                revenueToDate.Attributes["Label"] = "Revenue To Date";
                controlCollection.Add(revenueToDate);

                revenueAccountNumber = new TextBox();
                revenueAccountNumber.ID = InsightUtilities.Constants.RevenueAccountNumber;
                revenueAccountNumber.CssClass = "DataInput";
                revenueAccountNumber.Attributes["Label"] = "Account Number";
                controlCollection.Add(revenueAccountNumber);
            }
        }

		/// <summary>
		/// Setup the control tree to reflect the actual (and exact) layout of the controls within the CommonSearch.
		/// </summary>
		private void GenerateControlTree()
		{
			string searchClientId = ((Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey]).GetCachedObject(Constants.SearchButtonClientIDKey) as string;
			if (searchClientId == null)
				searchClientId = "expandingPanel_commonSearch_search";

			Table t1 = new Table();
			t1.Width = Unit.Percentage(100);
			t1.CssClass = "Search";
			t1.Attributes.Add("onkeypress", "return ClickButton(event, '" + searchClientId + "')");
			Controls.Add(t1);

			if(CategoryAndAccountFilterVisible || IncludeUserOrdersFilterVisible)
			{
				TableRow t1r1 = new TableRow();
				t1.Rows.Add(t1r1);

				if(CategoryAndAccountFilterVisible)
				{
                    TableCell t1r1c1 = new TableCell();
                    t1r1c1.HorizontalAlign = HorizontalAlign.Right;
                    t1r1c1.Text = "Category:\t\t";
                    t1r1.Cells.Add(t1r1c1);

                    TableCell t1r1c2 = new TableCell();
                    t1r1c2.HorizontalAlign = HorizontalAlign.Left;
                    t1r1c2.Controls.Add(category);
                    t1r1.Cells.Add(t1r1c2);

                    TableCell t1r1c3 = new TableCell();
					t1r1c3.HorizontalAlign = HorizontalAlign.Right;
					t1r1c3.Text = "Account #:";
					t1r1.Cells.Add(t1r1c3);

					TableCell t1r1c4 = new TableCell();
					t1r1c4.HorizontalAlign = HorizontalAlign.Left;
					t1r1c4.Controls.Add(accountNumber);
					t1r1.Cells.Add(t1r1c4);

				}
				else
				{
					TableCell t1r1c = new TableCell();
					t1r1c.ColumnSpan = 4;
					t1r1.Cells.Add(t1r1c);
				}

				if(IncludeUserOrdersFilterVisible)
				{

					TableCell t1r1c1 = new TableCell();
					t1r1c1.HorizontalAlign = HorizontalAlign.Right;
					t1r1c1.Text = "Include User Orders:";
					t1r1.Cells.Add(t1r1c1);

					TableCell t1r1c2 = new TableCell();
					t1r1c2.HorizontalAlign = HorizontalAlign.Left;
					t1r1c2.Controls.Add(includeUserOrders);
					t1r1.Cells.Add(t1r1c2);

				}
				else
				{
					TableCell t1r1c = new TableCell();
					t1r1c.ColumnSpan = 2;
					t1r1.Cells.Add(t1r1c);
				}

			}

			if( BudgetStartEndFilterVisible || BudgetEndingFilterVisible)
			{
				TableRow t1r1 = new TableRow();
				t1.Rows.Add(t1r1);

				if(BudgetStartEndFilterVisible)
				{
					TableCell t1r1c1 = new TableCell();
					t1r1c1.HorizontalAlign = HorizontalAlign.Right;
					t1r1c1.Text = "Budget Start:";
					t1r1.Cells.Add(t1r1c1);

					TableCell t1r1c2 = new TableCell();
					t1r1c2.HorizontalAlign = HorizontalAlign.Left;
					t1r1c2.Controls.Add(budgetStartDate);
					t1r1.Cells.Add(t1r1c2);

					TableCell t1r1c3 = new TableCell();
					t1r1c3.HorizontalAlign = HorizontalAlign.Right;
					t1r1c3.Text = "End:";
					t1r1.Cells.Add(t1r1c3);

					TableCell t1r1c4 = new TableCell();
					t1r1c4.HorizontalAlign = HorizontalAlign.Left;
					t1r1c4.Controls.Add(budgetEndDate);
					t1r1.Cells.Add(t1r1c4);
				}
				else
				{
					TableCell t1r1c = new TableCell();
					t1r1c.ColumnSpan = 4;
					t1r1.Cells.Add(t1r1c);
				}

				if(BudgetEndingFilterVisible )
				{

					TableCell t1r1c1 = new TableCell();
					t1r1c1.HorizontalAlign = HorizontalAlign.Right;
					t1r1c1.Text = "Budget Ending In:";
					t1r1.Cells.Add(t1r1c1);

					TableCell t1r1c2 = new TableCell();
					t1r1c2.HorizontalAlign = HorizontalAlign.Left;
					t1r1c2.Controls.Add(daysBudgetEnding);
					t1r1.Cells.Add(t1r1c2);

				}
				else
				{
					TableCell t1r1c = new TableCell();
					t1r1c.ColumnSpan = 2;
					t1r1.Cells.Add(t1r1c);
				}
			}
	
			if(SalaryOnFundExpiringFilterVisible || PayFromToDateFilterVisible)
			{
				TableRow t1r1 = new TableRow();
				t1.Rows.Add(t1r1);

				TableCell t1r1c1 = new TableCell();
				t1r1c1.HorizontalAlign = HorizontalAlign.Right;
				t1r1c1.Text = "Salary On Funds Ending In:";
				t1r1.Cells.Add(t1r1c1);

				TableCell t1r1c2 = new TableCell();
				t1r1c2.HorizontalAlign = HorizontalAlign.Left;
				t1r1c2.Controls.Add(salaryOnFundExpiring);
				t1r1.Cells.Add(t1r1c2);

				TableCell t1r1c3 = new TableCell();
				t1r1c3.HorizontalAlign = HorizontalAlign.Right;
				t1r1c3.Text = "Pay From:";
				t1r1.Cells.Add(t1r1c3);

				TableCell t1r1c4 = new TableCell();
				t1r1c4.HorizontalAlign = HorizontalAlign.Left;
				t1r1c4.Controls.Add(payFromDate);
				t1r1.Cells.Add(t1r1c4);

				TableCell t1r1c5 = new TableCell();
				t1r1c5.HorizontalAlign = HorizontalAlign.Right;
				t1r1c5.Text = "To:";
				t1r1.Cells.Add(t1r1c5);

				TableCell t1r1c6 = new TableCell();
				t1r1c6.HorizontalAlign = HorizontalAlign.Left;
				t1r1c6.Controls.Add(payToDate);
				t1r1.Cells.Add(t1r1c6);
			}

			if(EmployeeIdFilterVisible)
			{
				TableRow t1r1 = new TableRow();
				t1.Rows.Add(t1r1);

				TableCell t1r1c1 = new TableCell();
				t1r1c1.HorizontalAlign = HorizontalAlign.Right;
				t1r1c1.Text = "Employee Id:";
				t1r1.Cells.Add(t1r1c1);

				TableCell t1r1c2 = new TableCell();
				t1r1c2.HorizontalAlign = HorizontalAlign.Left;
				t1r1c2.Controls.Add(employeeId);
				t1r1.Cells.Add(t1r1c2);

//				Controls.Add(new LiteralControl(
//					"</td>\n" +
//					"\t\t<td align=\"right\" colspan=\"4\"> </td>\n"));
			
			}
			if(ExpenseDateFilterVisible)
			{
				TableRow t1r1 = new TableRow();
				t1.Rows.Add(t1r1);

				TableCell t1r1c1 = new TableCell();
				t1r1c1.HorizontalAlign = HorizontalAlign.Right;
				t1r1c1.Text = "Month from:";
				t1r1.Cells.Add(t1r1c1);

				TableCell t1r1c2 = new TableCell();
				t1r1c2.HorizontalAlign = HorizontalAlign.Left;
				t1r1c2.Controls.Add(expenseFromDate);
				t1r1.Cells.Add(t1r1c2);

				TableCell t1r1c3 = new TableCell();
				t1r1c3.HorizontalAlign = HorizontalAlign.Right;
				t1r1c3.Text = "Month to:";
				t1r1.Cells.Add(t1r1c3);

				TableCell t1r1c4 = new TableCell();
				t1r1c4.HorizontalAlign = HorizontalAlign.Left;
				t1r1c4.Controls.Add(expenseToDate);
				t1r1.Cells.Add(t1r1c4);
			}
            if (RevenueDateFilterVisible)
            {
                TableRow t1r1 = new TableRow();
                t1.Rows.Add(t1r1);

                TableCell cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Right;
                cell.Text = "Account Number:";
                t1r1.Cells.Add(cell);

                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Left;
                cell.Controls.Add(revenueAccountNumber);
                t1r1.Cells.Add(cell);

                TableCell t1r1c1 = new TableCell();
                t1r1c1.HorizontalAlign = HorizontalAlign.Right;
                t1r1c1.Text = "Revenue from:";
                t1r1.Cells.Add(t1r1c1);

                TableCell t1r1c2 = new TableCell();
                t1r1c2.HorizontalAlign = HorizontalAlign.Left;
                t1r1c2.Controls.Add(revenueFromDate);
                t1r1.Cells.Add(t1r1c2);

                TableCell t1r1c3 = new TableCell();
                t1r1c3.HorizontalAlign = HorizontalAlign.Right;
                t1r1c3.Text = "Revenue to:";
                t1r1.Cells.Add(t1r1c3);

                TableCell t1r1c4 = new TableCell();
                t1r1c4.HorizontalAlign = HorizontalAlign.Left;
                t1r1c4.Controls.Add(revenueToDate);
                t1r1.Cells.Add(t1r1c4);
            }
        }

		/// <summary>
		/// Helper method to load a drop-down-list with data.
		/// </summary>
		/// <param name="list">Reference to the drop-down-list to load</param>
		/// <param name="table">DataTable which contains data to load</param>
		/// <param name="textColumnName">Column Text</param>
		/// <param name="valueColumnName">Column Value</param>
		private static void LoadDropDownList(DropDownList list, DataTable table, string textColumnName, string valueColumnName)
		{
			if(list.Items.Count > 0)
				list.Items.Clear();

			list.Items.Add(CommonSearch.SelectPrompt);
			if(table.Rows.Count > 0)
			{
				foreach (DataRow row in table.Rows)
					list.Items.Add(new ListItem((string)row[textColumnName], row[valueColumnName].ToString()));
				list.SelectedIndex = 0;
				list.Enabled = (list.Items.Count > 0);
			}
			else
				list.Enabled = false;
		}
		#endregion

		#region Internal Methods
		/// <summary>
		/// This method is ONLY invoked by the associated designer to show the control contents at design time.
		/// </summary>
		internal void Design()
		{
			EnsureChildControls();
		}
		#endregion
	}
	#endregion

	#region Class PagerDesigner
	/// <summary>
	/// Designer associated with the Overview search control.
	/// </summary>
	/// <remarks>
	/// This class cannot be used directly.
	/// </remarks>
	public class OverviewSearchDesigner : ControlDesigner
	{
		#region Overrides
		/// <summary>
		/// Force the control to create its child controls for display at design time.
		/// </summary>
		/// <returns>HTML representation of the control</returns>
		public override string GetDesignTimeHtml()
		{
			((OverviewSearch)Component).Design();
			return base.GetDesignTimeHtml();
		}
		#endregion
	}
	#endregion
}
// --- EOF ---